package com.luisliuyi.demo.opencv;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback, Camera
        .PreviewCallback  {

  static {
    System.loadLibrary("native-lib");
  }

  private CameraHelper cameraHelper;
  int cameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
  SurfaceView surfaceView;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    surfaceView = findViewById(R.id.surfaceView);
    checkPermission();
    surfaceView.getHolder().addCallback(this);
    cameraHelper = new CameraHelper(cameraId);
    cameraHelper.setPreviewCallback(this);
    Utils.copyAssets(this, "lbpcascade_frontalface.xml");
  }

  public boolean checkPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
      requestPermissions(new String[]{
              Manifest.permission.READ_EXTERNAL_STORAGE,
              Manifest.permission.WRITE_EXTERNAL_STORAGE,
              Manifest.permission.CAMERA
      }, 1);
    }
    return false;
  }

  @Override
  protected void onResume() {
    super.onResume();
    //初始化
    init("/sdcard/lbpcascade_frontalface.xml");
    cameraHelper.startPreview();
  }

  @Override
  protected void onStop() {
    super.onStop();
    //释放
    release();
    cameraHelper.stopPreview();
  }

  @Override
  public void onPreviewFrame(byte[] data, Camera camera) {
    //传输数据
    postData(data, CameraHelper.WIDTH, CameraHelper.HEIGHT, cameraId);
  }

  @Override
  public void surfaceCreated(SurfaceHolder holder) {

  }

  @Override
  public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    setSurface(holder.getSurface());
  }

  @Override
  public void surfaceDestroyed(SurfaceHolder holder) {

  }

  @Override
  public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_UP) {
      cameraHelper.switchCamera();
      cameraId = cameraHelper.getCameraId();
    }
    return super.onTouchEvent(event);
  }

  /**
   * 初始化 追踪器
   * @param model
   */
  native void init(String model);

  /**
   * 设置画布
   *  ANativeWindow
   * @param surface
   */
  native void setSurface(Surface surface);

  /**
   * 处理摄像头数据
   * @param data
   * @param w
   * @param h
   * @param cameraId
   */
  native void postData(byte[] data, int w, int h, int cameraId);

  /**
   * 释放
   */
  native void release();
}